import Cookies from 'js-cookie'
import useUserStore from '@/store/modules/user'

const TokenKey = 'Admin-Token'

export function getToken() {
  return Cookies.get(TokenKey)
}

export function setToken(token) {
  return Cookies.set(TokenKey, token)
}

export function removeToken() {
  return Cookies.remove(TokenKey)
}

/**
 * 获取当前用户信息
 */
export function getCurrentUser() {
  const userStore = useUserStore()
  return userStore.userInfo
}

/**
 * 获取当前用户角色列表
 */
export function getCurrentRoles() {
  const userStore = useUserStore()
  return userStore.roles || []
}

/**
 * 获取当前用户权限列表
 */
export function getCurrentPermissions() {
  const userStore = useUserStore()
  return userStore.permissions || []
}

/**
 * 判断是否为超级管理员
 */
export function isSuperAdmin() {
  const roles = getCurrentRoles()
  return roles.includes('admin')
}

/**
 * 判断是否为质量管理员
 */
export function isQualityManager() {
  const roles = getCurrentRoles()
  return roles.includes('quality_manager') || isSuperAdmin()
}

/**
 * 判断是否为检验员
 */
export function isInspector() {
  const roles = getCurrentRoles()
  return roles.includes('inspector') || isQualityManager()
}

/**
 * 根据角色判断是否有权限访问指定功能
 * @param {string} feature 功能标识
 * @returns {boolean}
 */
export function hasFeatureAccess(feature) {
  // 超级管理员拥有所有权限
  if (isSuperAdmin()) {
    return true
  }

  const roleAccess = {
    // 基础数据管理权限
    'product:manage': ['admin', 'quality_manager'],
    'product:view': ['admin', 'quality_manager', 'inspector'],
    'process:manage': ['admin', 'quality_manager'],
    'process:view': ['admin', 'quality_manager', 'inspector'],
    'standard:manage': ['admin', 'quality_manager'],
    'standard:view': ['admin', 'quality_manager', 'inspector'],
    'equipment:manage': ['admin', 'quality_manager'],
    'equipment:view': ['admin', 'quality_manager', 'inspector'],

    // 质量检验权限
    'inspection:task:create': ['admin', 'quality_manager'],
    'inspection:task:assign': ['admin', 'quality_manager'],
    'inspection:task:view': ['admin', 'quality_manager', 'inspector'],
    'inspection:data:entry': ['admin', 'quality_manager', 'inspector'],
    'inspection:data:view': ['admin', 'quality_manager', 'inspector'],
    'inspection:defect:manage': ['admin', 'quality_manager'],
    'inspection:defect:view': ['admin', 'quality_manager', 'inspector'],

    // 不合格品管理权限
    'nonconforming:manage': ['admin', 'quality_manager'],
    'nonconforming:register': ['admin', 'quality_manager', 'inspector'],
    'nonconforming:view': ['admin', 'quality_manager', 'inspector'],

    // 质量证书权限
    'certificate:manage': ['admin', 'quality_manager'],
    'certificate:view': ['admin', 'quality_manager', 'inspector'],

    // 数据分析权限
    'analysis:full': ['admin', 'quality_manager'],
    'analysis:basic': ['admin', 'quality_manager', 'inspector'],

    // 系统管理权限
    'system:user:manage': ['admin'],
    'system:role:manage': ['admin'],
    'system:menu:manage': ['admin'],
    'system:config:manage': ['admin'],
    'system:view': ['admin', 'quality_manager']
  }

  const allowedRoles = roleAccess[feature]
  if (!allowedRoles) {
    return false
  }

  const currentRoles = getCurrentRoles()
  return allowedRoles.some(role => currentRoles.includes(role))
}

/**
 * 获取用户可见的菜单操作按钮
 * @param {string} module 模块名称
 * @returns {array} 可见的操作按钮列表
 */
export function getVisibleActions(module) {
  const userRoles = getCurrentRoles()
  
  // 超级管理员看到所有按钮
  if (isSuperAdmin()) {
    return ['add', 'edit', 'delete', 'view', 'export', 'import']
  }

  const actionAccess = {
    'product': {
      'quality_manager': ['add', 'edit', 'delete', 'view', 'export', 'import'],
      'inspector': ['view']
    },
    'process': {
      'quality_manager': ['add', 'edit', 'delete', 'view', 'export'],
      'inspector': ['view']
    },
    'standard': {
      'quality_manager': ['add', 'edit', 'delete', 'view', 'export'],
      'inspector': ['view']
    },
    'inspection': {
      'quality_manager': ['add', 'edit', 'delete', 'view', 'export', 'assign'],
      'inspector': ['add', 'edit', 'view']
    },
    'defect': {
      'quality_manager': ['add', 'edit', 'delete', 'view', 'export'],
      'inspector': ['view']
    },
    'certificate': {
      'quality_manager': ['add', 'edit', 'delete', 'view', 'export', 'generate'],
      'inspector': ['view']
    }
  }

  const moduleAccess = actionAccess[module] || {}
  let visibleActions = []

  userRoles.forEach(role => {
    if (moduleAccess[role]) {
      visibleActions = [...new Set([...visibleActions, ...moduleAccess[role]])]
    }
  })

  return visibleActions
}

/**
 * 检查是否有指定权限
 * @param {string|array} permissions 权限标识
 * @returns {boolean}
 */
export function hasPermission(permissions) {
  if (isSuperAdmin()) {
    return true
  }

  const userPermissions = getCurrentPermissions()
  const checkPermissions = Array.isArray(permissions) ? permissions : [permissions]
  
  return checkPermissions.some(permission => userPermissions.includes(permission))
}

/**
 * 检查是否有指定角色
 * @param {string|array} roles 角色标识
 * @returns {boolean}
 */
export function hasRole(roles) {
  const userRoles = getCurrentRoles()
  const checkRoles = Array.isArray(roles) ? roles : [roles]
  
  return checkRoles.some(role => userRoles.includes(role))
}

export default {
  getCurrentUser,
  getCurrentRoles,
  getCurrentPermissions,
  isSuperAdmin,
  isQualityManager,
  isInspector,
  hasFeatureAccess,
  getVisibleActions,
  hasPermission,
  hasRole
}
